#include <func.h>

int main(int argc,char **argv)
{
    ARGS_CHECK(argc,3);
    int socketFd;
    socketFd = socket(AF_INET,SOCK_STREAM,0);
    ERROR_CHECK(socketFd,-1,"socket");
    printf("socketFd:%d\n",socketFd);

    struct sockaddr_in ser;
    ser.sin_family = AF_INET;
    ser.sin_port = htons(atoi(argv[2]));
    ser.sin_addr.s_addr = inet_addr(argv[1]);

    int ret;
    
    //通过setsockopt 设置端口关闭后不经历time-wait过程
    int reuse = 1;
    ret = setsockopt(socketFd,SOL_SOCKET,SO_REUSEADDR,(const char*)&reuse,sizeof(int));
    ERROR_CHECK(ret,-1,"setsockopt");

    ret = bind(socketFd,(struct sockaddr*)&ser,sizeof(ser));
    ERROR_CHECK(ret,-1,"bind");

    listen(socketFd,10);

    int newFd;
    struct sockaddr_in client;
    char buf[1000];
    int epfd = epoll_create(1);
    
    struct epoll_event event,evs[3];
    event.data.fd = STDIN_FILENO;
    event.events = EPOLLIN;
    ret = epoll_ctl(epfd,EPOLL_CTL_ADD,socketFd,&event);
    ERROR_CHECK(ret,-1,"epoll_ctl");

    int readyFdNum;
    while(1)
    {
        readyFdNum = epoll_wait(epfd,evs,3,-1);//最后一个参数是timeout，-1表示一直阻塞
        for(int i = 0;i<readyFdNum;i++)
        {
            //遍历evs，
            //socketFd 有新用户接入
            if(evs[i].data.fd == socketFd)
            {
                bzero(&client,sizeof(client));
                socklen_t len = sizeof(client);
                newFd = accept(socketFd,(struct sockaddr*)&client,&len);
                ERROR_CHECK(newFd,-1,"accept");
                printf("client ip:%s,client prot:%d\n",inet_ntoa);
                
                event.data.fd = newFd;
                ret = epoll_ctl(epfd,EPOLL_CTL_ADD,newFd,&event);
                ERROR_CHECK(ret,-1,"epoll_ctl");
                
            }
            //newFd 从客户接收信息
            if(evs[i].data.fd == newFd)
            {
                bzero(buf,sizeof(buf));
                ret = recv(newFd,buf,sizeof(buf),0);
                if(!ret)
                {
                    printf("lose client, disconnected...\n");
                    event.data.fd
                    
                }
                else
                {}
            }
            //STDIN 向客户发送信息
            
    }

    
    close(epfd);
    close(socketFd);
    return 0;
}

